import json
import logging
import secrets
from copy import deepcopy
from datetime import datetime, timedelta

import requests
from django.core.cache import cache
from django.core.handlers.wsgi import WSGIRequest
from django.db import transaction
from django.db.models import Sum, Q, F, Value, QuerySet, Count
from django.db.models.functions import TruncMonth, TruncDay
from django.http import JsonResponse
from django.views import View
from django.views.decorators.http import require_http_methods
from rest_framework import status
from rest_framework.parsers import JSONParser

from jqdelivery.error import UserDeliveryNullErr, UserDeliveredErr
from jqdelivery.models import (
    UserDeliveryOrder,
    UserDeliveryOrderState,
    UserExpressInfo,
    UserExpress,
)
from jqdelivery.serializers import UserExpressInfoSerializer
from jqexception.jqexecption import (
    ValueErr,
    jq_try,
    UnknowErr,
    RightErr,
    NullErr,
)
from jqgame.basegame import GameType
from jqgame.utils import get_game_type_table_name
from jqpackage.models import UserPackageGoods, UserPackageGoodsState
from jqpage.pagination import JQPagination
from juqiadmin.errer import GameRuleNullErr
from quanjushang.models import QuanjushangGame
from warehouse.models import GoodLevel
from wxcloudrun.models import (
    get_web_settings,
)
from wxcloudrun.ser import WebSettingsSerializer
from wxuser.models import (
    Users,
    UserRechargeOrder,
    UserRechargeType,
    OrderState,
    UserState,
    UserOrder,
    UserRefinedOrder,
    UserRefinedOrderGoods,
    UserScoreRecord,
    UserShipmentOrder,
)
from wxuser.serializers import (
    UserResultSerializer,
)
from yifanshang.models import YifanshangGame
from .auth import flush_admin_cache, login_auth, check_admin
from .common.filters import (
    StringFilterResolver,
    IntFilterResolver,
    DateTimeRangeFilterResolver,
    BoolFilterResolver,
    join_filters,
    EnumFilterResolver,
)
from .common.utlis import get_web_settings_statistical_exclude_user_uid_list
from .constants import Constants
from .models import (
    Finance,
    FinanceType,
    GameRule,
    JuqiAdmin,
    init_admin,
    ModifyType,
    UserWithdraw,
    admin_modify_user_value,
    get_wxuser_recharge_withdraw_finance,
    FinanceStatus,
    get_wxuser_finance,
    update_finnce_profit,
    FinanceRechargeRaffleCostType,
)
from .serializers import (
    FinanceSerializer,
    GameRuleRequestBodySerializer,
    GameRuleSerializer,
    JuqiAdminSerializer,
    FinanceMonthSerializer,
    FinanceDaySerializer,
    UserProfitDaySerializer,
    UserProfitSumSerializer,
    UserPackageDetailedSerializer,
    UserRankRechargeSerializer,
    UserRankConsumptionSerializer,
    UserRankProfitSerializer,
    UserRecordRechargeSerializer,
    UserRecordWithdrawSerializer,
    UserExpenseRecordSerializer,
    UserExpenseRecordGoodsSerializer,
    UserRecordRefinedSerializer,
    UserDeliveryOrderDetailedGoodsSerializer,
    UserRaffleRecordGoodsSerializer,
    UserRaffleRecordSerializer,
    UserRecordPurchaseGoodsSerializer,
    UserRecordPersonalDetailsSerializer,
    UserPackagesGameLevelNameSerializer,
    UserRecordScoreSerializer,
    UserDeliveryOrderSerializer,
    UserDeliveryOrderDetailedSerializer,
    GameRuleOptionSerializer,
    HomeFinSerializer,
    HomeUserSerializer,
)
from .wxapi import tcb_token_url, tcb_download_url

logger = logging.getLogger("log")


# Create your views here.
@require_http_methods(["POST"])
@jq_try
def login(request: WSGIRequest, _, *args, **kwargs):
    init_admin()
    d = JSONParser().parse(request)

    right_admin = JuqiAdmin.objects.filter(user=d.get("user", "")).first()
    right_admin_s = JuqiAdminSerializer(right_admin)

    if not right_admin:
        raise RightErr

    for field in ["user", "password"]:
        if d[field] != right_admin_s.data[field]:
            raise RightErr

    _token = request.session.get("login_token")
    if _token:
        flush_admin_cache(_token, deepcopy(right_admin_s.data))
        return JsonResponse(
            {"code": "0", "info": "already login"}, status=status.HTTP_200_OK
        )

    token = secrets.token_hex(nbytes=32)
    request.session["login_token"] = token
    cache.set(token, deepcopy(right_admin_s.data), 15 * 60)

    return JsonResponse(
        {"code": "0", "info": "login success"}, status=status.HTTP_200_OK
    )


@require_http_methods(["POST"])
@login_auth
def logout(request: WSGIRequest, _, *args, **kwargs):
    token = request.session.get("login_token", None)
    if not token:
        raise RightErr

    request.session.pop("login_token", None)
    cache.delete(token)

    return JsonResponse(
        {"code": "0", "info": "logout success"}, status=status.HTTP_200_OK
    )


@require_http_methods(["POST"])
@login_auth
def tcb_token(request: WSGIRequest, _, *args, **kwargs):
    body = JSONParser().parse(request)
    params = {"env": cache.get("ENV_ID"), "path": body["path"]}
    logger.debug(params)
    r = requests.post(tcb_token_url, json=params)
    d = json.loads(r.content)
    logger.debug(d)

    return JsonResponse(d, status=status.HTTP_200_OK)


@require_http_methods(["POST"])
@login_auth
def tcb_download(request: WSGIRequest, _, *args, **kwargs):
    # https://developers.weixin.qq.com/miniprogram/dev/wxcloudrun/src/development/storage/service/download.html
    body = JSONParser().parse(request)
    params = {"env": cache.get("ENV_ID"), "file_list": body["file_list"]}
    logger.debug(params)
    r = requests.post(tcb_download_url, json=params)
    d = json.loads(r.content)
    logger.debug(d)

    return JsonResponse(d, status=status.HTTP_200_OK)


def _gen_user():
    inviter_user = Users(
        openid="2233121212121212121211212",
        nickname="user",
        realname="张三",
        telephone=111111111111,
    )
    inviter_user.save()
    for i in range(10):
        Users(
            openid="2233121212121212121211212" + str(i),
            nickname="user_" + str(i),
            realname="张" + str(i),
            inviter_uuid=inviter_user.uuid,
            telephone=111111111111 + i,
        ).save()


class UserView(View):
    filters = {
        "uid": StringFilterResolver(field_name="id"),
        "nickname": StringFilterResolver(),
        "telephone": IntFilterResolver(),
        "is_daili": BoolFilterResolver(),
        "createdAt": DateTimeRangeFilterResolver(),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(UserResultSerializer)

        _query_set = Users.objects.filter(deleted=False)

        _query_set = join_filters(_query_set, request, self.filters)

        _query_set = _query_set.order_by("-id").all()
        _data = paginator.paginate(_query_set, request)

        return JsonResponse(_data, status=status.HTTP_200_OK)

    @check_admin
    @transaction.atomic
    def delete(self, request: WSGIRequest, *args, **kwargs):
        uuid = request.GET.get("uuid")

        if uuid is None:
            raise ValueErr

        Users.objects.select_for_update()
        rows = (
            Users.objects.filter(deleted=False).filter(uuid=uuid).update(deleted=True)
        )
        if rows > 0:
            return JsonResponse({"code": 0, "msg": "ok"}, status=status.HTTP_200_OK)
        raise UnknowErr


class UserDetailsView(View):
    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        user = StringFilterResolver().filter(Users.objects, "uuid", request).first()
        _data = UserResultSerializer(user).data

        if _data is None:
            raise NullErr
        return JsonResponse({"code": 0, "msg": "ok", "data": _data})


class UserStoredMoneyRechargeView(View):
    """
    用户充值视图
    """

    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        user_info = kwargs.get("user_info")

        if user_info is None or user_info.uuid is None:
            raise RightErr
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        stored_money = data.get("stored_money")

        if user_uuid is None or stored_money is None or stored_money <= 0:
            raise ValueErr

        admin = JuqiAdmin.objects.get(uuid=user_info.uuid)
        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )
        if user is None or admin is None:
            raise ValueErr

        # 变更用户金额
        admin_modify_user_value(
            admin, user, ModifyType.stored_money, stored_money, f"管理员{admin.user}余额充值"
        )
        # 添加充值订单
        UserRechargeOrder(
            openid=user.openid,
            total_fee=stored_money,
            state=OrderState.success.value,
            recharge_type=UserRechargeType.admin,
            admin_uuid=admin.uuid,
        ).save()

        finance = get_wxuser_recharge_withdraw_finance(user_uuid)

        finance.all_admin_recharge += stored_money

        finance.save()

        user.save()
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserStoredMoneyRefundView(View):
    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        user_info = kwargs.get("user_info")

        if user_info is None or user_info.uuid is None:
            raise RightErr
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        stored_money = data.get("stored_money")

        if user_uuid is None or stored_money is None or stored_money <= 0:
            raise ValueErr

        admin = JuqiAdmin.objects.get(uuid=user_info.uuid)

        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )
        if user is None or admin is None:
            raise ValueErr

        if user.stored_money < stored_money:
            raise ValueErr

        finance = get_wxuser_recharge_withdraw_finance(user_uuid)

        # 变更用户金额
        admin_modify_user_value(
            admin, user, ModifyType.stored_money, -stored_money, f"管理员{admin.user}余额退款"
        )

        finance.all_admin_recharge -= stored_money

        finance.save()
        user.save()
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserHunjingRechargeView(View):
    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        user_info = kwargs.get("user_info")

        if user_info is None or user_info.uuid is None:
            raise RightErr
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        hunjing = data.get("hunjing")

        if user_uuid is None or hunjing is None or hunjing <= 0:
            raise ValueErr

        admin = JuqiAdmin.objects.get(uuid=user_info.uuid)
        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )
        if user is None or admin is None:
            raise ValueErr
        # 变更用户金额
        admin_modify_user_value(
            admin, user, ModifyType.hunjing, hunjing, f"管理员{admin.user}魂晶充值"
        )
        fin = get_wxuser_recharge_withdraw_finance(
            user.uuid, raffle_cost_type=FinanceRechargeRaffleCostType.hunjing
        )

        _fin = Finance.objects.filter(uuid=fin.uuid).select_for_update().first()

        _fin.all_raffle_cost += hunjing

        update_finnce_profit(_fin)

        _fin.save()

        user.save()
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserHunjingDeductionView(View):
    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        user_info = kwargs.get("user_info")

        if user_info is None or user_info.uuid is None:
            raise RightErr
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        hunjing = data.get("hunjing")

        if user_uuid is None or hunjing is None or hunjing <= 0:
            raise ValueErr

        admin = JuqiAdmin.objects.get(uuid=user_info.uuid)
        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )

        if user is None or admin is None:
            raise ValueErr

        if user.hunjing < hunjing:  # 防止超额扣除
            raise ValueErr

        # 变更用户金额
        admin_modify_user_value(
            admin, user, ModifyType.hunjing, -hunjing, f"管理员{admin.user}魂晶扣除"
        )

        fin = get_wxuser_recharge_withdraw_finance(
            user.uuid, raffle_cost_type=FinanceRechargeRaffleCostType.hunjing
        )

        _fin = Finance.objects.filter(uuid=fin.uuid).select_for_update().first()

        _fin.all_raffle_cost -= hunjing

        update_finnce_profit(_fin)

        _fin.save()

        user.save()
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserHunjingWithdrawView(View):
    """
    魂晶提现请求
    """

    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        user_info = kwargs.get("user_info")

        if user_info is None or user_info.uuid is None:
            raise RightErr

        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        hunjing = data.get("hunjing")

        if user_uuid is None or hunjing is None or hunjing <= 0:
            raise ValueErr

        (withdraw_money, mod) = divmod(hunjing, Constants.HUNJING_WITHDRAW_RATIO)
        if mod != 0:
            raise ValueErr

        admin = JuqiAdmin.objects.get(uuid=user_info.uuid)
        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )
        if user is None or admin is None:
            raise ValueErr

        # 魂晶提现金额超过魂晶所剩数量
        if user.hunjing < hunjing:
            raise ValueErr

        _old_hunjing = user.hunjing
        _new_hunjing = _old_hunjing - hunjing

        # 变更用户魂晶数量
        admin_modify_user_value(
            admin, user, ModifyType.hunjing, -hunjing, f"管理员{admin.user}魂晶提现"
        )
        # 创建用户提现信息

        UserWithdraw(
            user_uuid=user.uuid,
            admin_uuid=admin.uuid,
            old_hunjing=_old_hunjing,
            new_hunjing=_new_hunjing,
            withdraw_money=withdraw_money,
        ).save()

        finance = get_wxuser_recharge_withdraw_finance(user.uuid)
        finance.all_withdraw += withdraw_money
        finance.save()
        user.save()
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserScoreRechargeView(View):
    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        user_info = kwargs.get("user_info")

        if user_info is None or user_info.uuid is None:
            raise RightErr
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        score = data.get("score")

        if user_uuid is None or score is None or score <= 0:
            raise ValueErr

        admin = JuqiAdmin.objects.get(uuid=user_info.uuid)

        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )

        if user is None or admin is None:
            raise ValueErr
        # 变更用户积分
        admin_modify_user_value(
            admin, user, ModifyType.score, score, f"管理员{admin.user}积分充值"
        )
        fin = get_wxuser_recharge_withdraw_finance(
            user.uuid, raffle_cost_type=FinanceRechargeRaffleCostType.score
        )

        _fin = Finance.objects.filter(uuid=fin.uuid).select_for_update().first()

        _fin.all_raffle_cost += score

        update_finnce_profit(_fin)

        _fin.save()
        user.save()
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserScoreDeductionView(View):
    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        user_info = kwargs.get("user_info")

        if user_info is None or user_info.uuid is None:
            raise RightErr
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        score = data.get("score")

        if user_uuid is None or score is None or score <= 0:
            raise ValueErr

        admin = JuqiAdmin.objects.get(uuid=user_info.uuid)
        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )
        if user is None or admin is None:
            raise ValueErr

        if user.score < score:
            raise ValueErr

        # 变更用户金额
        admin_modify_user_value(
            admin, user, ModifyType.score, -score, f"管理员{admin.user}积分扣除"
        )

        fin = get_wxuser_recharge_withdraw_finance(
            user.uuid, raffle_cost_type=FinanceRechargeRaffleCostType.score
        )

        _fin = Finance.objects.filter(uuid=fin.uuid).select_for_update().first()

        _fin.all_raffle_cost -= score

        update_finnce_profit(_fin)

        _fin.save()

        user.save()
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserDailiView(View):
    """
    用户更新是否代理
    """

    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        daili = data.get("daili")

        if user_uuid is None or user_uuid == "":
            raise ValueErr

        if daili is None or daili == "":
            raise ValueErr
        daili = bool(daili)

        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )

        if user is None:
            raise ValueErr

        user.is_daili = daili
        user.save()

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserDisableView(View):
    """
    用户更新禁用状态
    """

    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        disable = data.get("disable")

        if user_uuid is None or user_uuid == "":
            raise ValueErr

        if disable is None or disable == "":
            raise ValueErr

        _disable = bool(disable)

        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )
        if user is None:
            raise ValueErr

        if _disable:
            user.state = UserState.block
        else:
            user.state = UserState.normal

        user.save()

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserInviterView(View):
    """
    用户更新禁用状态
    """

    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        inviter_uid = data.get("inviter_uid")

        if user_uuid is None or user_uuid == "":
            raise ValueErr

        if inviter_uid is None or inviter_uid == "":
            raise ValueErr

        inviter_user = (
            Users.objects.filter(deleted=False).filter(id=inviter_uid).first()
        )

        if inviter_user is None:
            raise ValueErr

        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )

        if user is None:
            raise ValueErr

        user.inviter_uuid = inviter_user.uuid

        user.save()

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserProfitView(View):
    """用户盈亏"""

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        quanjushang_types = [
            GameType.quanjushang.value,
            GameType.wuxianshang_boss.value,
        ]
        wuxianshang_types = [GameType.wuxianshang.value]
        yifanshang_types = [GameType.yifanshang.value]

        user_uuid = request.GET.get("user_uuid")
        if user_uuid is None:
            raise ValueErr
        user = Users.objects.filter(deleted=False).filter(uuid=user_uuid).first()
        if user is None:
            raise NullErr

        _user_finance_query = (
            Finance.objects.filter(deleted=False)
            .filter(finance_type=FinanceType.wxuser.value)
            .filter(user_uuid=user.uuid)
        )
        _user_finance_query = DateTimeRangeFilterResolver(
            "%Y-%m-%d", field_name="createdAt"
        ).filter(_user_finance_query, "date", request)

        _sum = (
            Finance.objects.filter(deleted=False)
            .filter(finance_type=FinanceType.wxuser.value)
            .filter(user_uuid=user.uuid)
            .values("user_uuid")
            .annotate(
                user_cost=Value(
                    user.stored_money + user.hunjing,
                ),
                user_score=Value(user.score),
                user_package_amount=Value(user.package_amount),
                wx_recharge=Sum("all_recharge"),
                admin_recharge=Sum("all_admin_recharge"),
                whole_recharge=Sum(F("all_recharge") + F("all_admin_recharge")),
                whole_withdraw=Sum("all_withdraw"),
                whole_shipper_cost=Sum("all_delivery_amount"),
                wuxianshang_raffle_income=Sum(
                    "all_raffle_income",
                    filter=Q(game_type__in=wuxianshang_types),
                ),
                wuxianshang_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(game_type__in=wuxianshang_types),
                    default=0,
                ),
                quanjushang_raffle_income=Sum(
                    "all_raffle_income",
                    filter=Q(game_type__in=quanjushang_types),
                    default=0,
                ),
                quanjushang_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(game_type__in=quanjushang_types),
                    default=0,
                ),
                yifanshang_raffle_income=Sum(
                    "all_raffle_income",
                    filter=Q(game_type__in=yifanshang_types),
                    default=0,
                ),
                yifanshang_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(game_type__in=yifanshang_types),
                    default=0,
                ),
                hunjing_recharge_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(raffle_cost_type=FinanceRechargeRaffleCostType.hunjing),
                    default=0,
                ),
                score_recharge_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(raffle_cost_type=FinanceRechargeRaffleCostType.score),
                    default=0,
                ),
                whole_raffle_income=Sum("all_raffle_income"),
                whole_raffle_cost=Sum("all_raffle_cost"),
                whole_raffle_profit=Sum("all_raffle_profit"),
            )
            .values(
                "user_cost",  # 账户剩余
                "user_score",  # 用户积分
                "user_package_amount",  # 用户赏柜价值
                "wx_recharge",  # 后台直冲累计充值
                "admin_recharge",  # 人工充值累计充值
                "whole_recharge",  # 累计充值
                "whole_withdraw",  # 累计提现
                "whole_shipper_cost",  # 发货价值
                "wuxianshang_raffle_income",  # 无限赏累计消费流水
                "wuxianshang_raffle_cost",  # 无限赏累计产出
                "quanjushang_raffle_income",  # 全局赏累计消费流水
                "quanjushang_raffle_cost",  # 全局赏累计产出
                "yifanshang_raffle_income",  # 一番赏累计消费流水
                "yifanshang_raffle_cost",  # 一番赏累计产出
                "hunjing_recharge_raffle_cost",  # 魂晶充值累计产出
                "score_recharge_raffle_cost",  # 积分充值累计产出
                "whole_raffle_income",  # 累计消费流水
                "whole_raffle_cost",  # 累计产出
                "whole_raffle_profit",  # 实际亏损
            )
        )

        _days = (
            _user_finance_query.all()
            .annotate(date=TruncDay("createdAt"))
            .values("date")
            .annotate(
                user_id=Value(user.id),
                user_name=Value(user.nickname),
                user_head_url=Value(user.head_url),
                wx_recharge=Sum("all_recharge"),
                admin_recharge=Sum("all_admin_recharge"),
                whole_recharge=Sum(F("all_recharge") + F("all_admin_recharge")),
                whole_withdraw=Sum("all_withdraw"),
                whole_shipper_cost=Sum("all_delivery_amount"),
                wuxianshang_raffle_income=Sum(
                    "all_raffle_income",
                    filter=Q(game_type__in=wuxianshang_types),
                    default=0,
                ),
                wuxianshang_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(game_type__in=wuxianshang_types),
                    default=0,
                ),
                quanjushang_raffle_income=Sum(
                    "all_raffle_income",
                    filter=Q(game_type__in=quanjushang_types),
                    default=0,
                ),
                quanjushang_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(game_type__in=quanjushang_types),
                    default=0,
                ),
                yifanshang_raffle_income=Sum(
                    "all_raffle_income",
                    filter=Q(game_type__in=yifanshang_types),
                    default=0,
                ),
                yifanshang_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(game_type__in=yifanshang_types),
                    default=0,
                ),
                hunjing_recharge_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(raffle_cost_type=FinanceRechargeRaffleCostType.hunjing),
                    default=0,
                ),
                score_recharge_raffle_cost=Sum(
                    "all_raffle_cost",
                    filter=Q(raffle_cost_type=FinanceRechargeRaffleCostType.score),
                    default=0,
                ),
                whole_raffle_income=Sum("all_raffle_income"),
                whole_raffle_cost=Sum("all_raffle_cost"),
                whole_raffle_profit=Sum("all_raffle_profit"),
            )
            .values(
                "date",  # 当日时间
                "user_id",  # 用户id
                "user_name",  # 用户名称
                "user_head_url",  # 用户头像地址
                "whole_shipper_cost",  # 当日赏品发货价值
                "wx_recharge",  # 当日后台直冲
                "admin_recharge",  # 人工充值
                "whole_recharge",  # 当日总充值
                "whole_withdraw",  # 当日总提现
                "wuxianshang_raffle_income",  # 当日无限赏消费
                "wuxianshang_raffle_cost",  # 当日无限赏产出
                "quanjushang_raffle_income",  # 当日全局赏消费
                "quanjushang_raffle_cost",  # 当日全局赏产出
                "yifanshang_raffle_income",  # 当日一番赏消费
                "yifanshang_raffle_cost",  # 当日一番赏产出
                "hunjing_recharge_raffle_cost",  # 魂晶充值累计产出
                "score_recharge_raffle_cost",  # 积分充值累计产出
                "whole_raffle_income",  # 当日总消费
                "whole_raffle_cost",  # 当日总产出
                "whole_raffle_profit",  # 当日总盈亏
            )
            .order_by("-date")
        )
        pagination = JQPagination(UserProfitDaySerializer)
        # for day in _days:
        #     day["whole_packages_cost"] = calculate_UserPackage_sum_price_by_date(
        #         user_uuid=user.uuid, sum_date=day["date"]
        #     )
        _days_data = pagination.paginate(_days, request)
        _sum_ser = []
        for s in _sum:
            _sum_ser.append(UserProfitSumSerializer(s).data)

        _data = {
            "code": 0,
            "msg": "ok",
            "data": {"sum": _sum_ser[0], "days": _days_data},
        }
        return JsonResponse(
            _data,
            status=status.HTTP_200_OK,
        )


def _check_digit(id_number):
    """通过身份证号获取校验码"""
    check_sum = 0
    for i in range(0, 17):
        check_sum += ((1 << (17 - i)) % 11) * int(id_number[i])
    check_digit = (12 - (check_sum % 11)) % 11
    return check_digit if check_digit < 10 else "X"


class UserRealView(View):
    """
    用户实名认证
    """

    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        data: dict = JSONParser().parse(request)

        user_uuid = data.get("user_uuid")
        real_name = data.get("real_name")
        idcard_num = data.get("idcard_num")

        if user_uuid is None or user_uuid == "":
            raise ValueErr

        if real_name is None or real_name == "":
            raise ValueErr

        if idcard_num is None or idcard_num == "":
            raise ValueErr

        if not _check_digit(idcard_num):
            raise ValueErr

        user = (
            Users.objects.filter(deleted=False)
            .filter(uuid=user_uuid)
            .select_for_update()
            .first()
        )
        if user is None:
            raise ValueErr

        user.realname = real_name
        user.idcard_num = idcard_num
        user.is_real = True

        user.save()

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"user": UserResultSerializer(user).data}},
            status=status.HTTP_200_OK,
        )


class UserPackagesView(View):
    """用户赏柜详情"""

    filters = {
        "user_uuid": StringFilterResolver(required=True),
        "good_level_title": StringFilterResolver(),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(UserPackageDetailedSerializer)
        _query_set = UserPackageGoods.objects.filter(deleted=False).filter(
            state__in=[UserPackageGoodsState.unhandled, UserPackageGoodsState.lock]
        )
        _query_set = join_filters(_query_set, request, self.filters)
        _query_set = _query_set.order_by("-createdAt").all()
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserPackagesGameLevelNameView(View):
    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        _title_list = GoodLevel.objects.filter(deleted=False).values("title")
        _list = []

        for title in _title_list:
            _list.append(UserPackagesGameLevelNameSerializer(title).data)

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"list": _list}},
            status=status.HTTP_200_OK,
        )


class UserExpenseRecordView(View):
    """用户消费记录"""

    _filters = {
        "user_uuid": StringFilterResolver(required=True),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        """
        用户消费记录
        """
        _query_set = UserOrder.objects.filter(deleted=False)
        _query_set = join_filters(_query_set, request, self._filters)
        _query_set = _query_set.order_by("-createdAt").all()
        paginator = JQPagination(UserExpenseRecordSerializer)
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserExpenseRecordGoodsView(View):
    """用户消费记录详细"""

    _filters = {
        "order_uuid": StringFilterResolver(required=True),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        """
        用户消费记录详细
        """
        _query_set = UserPackageGoods.objects.filter(deleted=False)
        _query_set = join_filters(_query_set, request, self._filters)
        _query_set = _query_set.extra(
            select={
                "name": "JuqiGood.name",
                "display_url": "JuqiGood.display_url",
                "price": "JuqiGood.price",
                "recovery_price": "JuqiGood.recovery_price",
                "game_type": "JuqiGood.game_type",
            },
            tables=["JuqiGood"],
            where=["JuqiGood.uuid=UserPackageGoods.good_uuid"],
        )
        _query_set = _query_set.values(
            "name",
            "display_url",
            "price",
            "recovery_price",
            "game_type",
            "good_level_title",
            "order_num",
            "createdAt",
        ).annotate(count=Value(1))
        _query_set = _query_set.order_by("-createdAt").all()
        _list = []
        sum_price = 0

        for record_goods in _query_set:
            _record_goods = UserExpenseRecordGoodsSerializer(record_goods).data
            price = _record_goods["price"]  # 获取价格
            sum_price += price  # 统计价格
            _list.append(_record_goods)

        _data = {
            "code": 0,
            "msg": "ok",
            "data": {"list": _list, "sum_price": sum_price, "sum_count": len(_list)},
        }

        return JsonResponse(
            _data,
            status=status.HTTP_200_OK,
        )


class FinanceMonthView(View):
    """月账单"""

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(FinanceMonthSerializer)

        _query_set = (
            Finance.objects.filter(deleted=False)
            .filter(finance_type=FinanceType.wxuser.value)
            .filter(finance_status=FinanceStatus.user)
        )
        _query_set = _query_set.annotate(date=TruncMonth("createdAt")).values("date")
        _query_set = DateTimeRangeFilterResolver("%Y-%m").filter(
            _query_set, "date", request
        )
        # if len(uuid_list) > 0:
        #     _query_set = _query_set.exclude(user_uuid__in=uuid_list)
        objs = (
            _query_set.all()
            .annotate(
                raffle_income=Sum("all_raffle_income"),
                raffle_cost=Sum("all_raffle_cost"),
                raffle_profit=Sum("all_raffle_profit"),
            )
            .values("date", "raffle_income", "raffle_cost", "raffle_profit")
            .order_by("-date")
        )

        _data = paginator.paginate(objs, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class FinanceDayView(View):
    """日账单"""

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(FinanceDaySerializer)

        _query_set = (
            Finance.objects.filter(deleted=False)
            .filter(finance_type=FinanceType.wxuser.value)
            .filter(finance_status=FinanceStatus.user)
        )
        _query_set = _query_set.annotate(date=TruncDay("createdAt")).values("date")
        _query_set = DateTimeRangeFilterResolver("%Y-%m-%d").filter(
            _query_set, "date", request
        )

        objs = (
            _query_set.annotate(
                raffle_income=Sum("all_raffle_income"),
                raffle_cost=Sum("all_raffle_cost"),
                raffle_profit=Sum("all_raffle_profit"),
            )
            .values("date", "raffle_income", "raffle_cost", "raffle_profit")
            .order_by("-date")
        )

        _data = paginator.paginate(objs, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserRankRechargeView(View):
    """充值排行榜"""

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(UserRankRechargeSerializer)
        uid = IntFilterResolver().resolve_argument("uid", request)
        _query_set = Finance.objects.filter(deleted=False).filter(
            finance_type=FinanceType.wxuser.value
        )
        date_resolver = DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt")
        filters = {"date": date_resolver}
        if date_resolver.supports_parameter("date", request):
            _query_set = join_filters(_query_set, request, filters)
        else:
            _date = datetime.now()
            _query_set = (
                _query_set.filter(createdAt__year=_date.year)
                .filter(createdAt__month=_date.month)
                .filter(createdAt__day=_date.day)
            )

        if uid is not None:
            user = Users.objects.filter(deleted=False).filter(id=uid).first()
            user_uuid = None
            if user is not None:
                user_uuid = user.uuid
            _query_set = _query_set.filter(user_uuid=user_uuid)
        _query_set = (
            _query_set.exclude(user_uuid=None)
            .values("user_uuid")
            .annotate(
                whole_recharge=Sum(F("all_recharge") + F("all_admin_recharge")),
            )
            .values(
                "user_uuid",
                "whole_recharge",
            )
            .filter(whole_recharge__gt=0)
            .order_by("-whole_recharge")
        )
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserRankConsumptionView(View):
    """消费排行榜"""

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(UserRankConsumptionSerializer)
        uid = IntFilterResolver().resolve_argument("uid", request)
        game_type_value = EnumFilterResolver(GameType).resolve_argument(
            "game_type", request
        )
        _query_set = Finance.objects.filter(deleted=False).filter(
            finance_type=FinanceType.wxuser.value
        )
        if game_type_value is not None:
            _query_set = _query_set.filter(game_type=game_type_value)

        date_resolver = DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt")
        filters = {"date": date_resolver}
        if date_resolver.supports_parameter("date", request):
            _query_set = join_filters(_query_set, request, filters)
        else:
            _date = datetime.now()
            _query_set = (
                _query_set.filter(createdAt__year=_date.year)
                .filter(createdAt__month=_date.month)
                .filter(createdAt__day=_date.day)
            )
        if uid is not None:
            user = Users.objects.filter(deleted=False).filter(id=uid).first()
            user_uuid = None
            if user is not None:
                user_uuid = user.uuid
            _query_set = _query_set.filter(user_uuid=user_uuid)
        _query_set = (
            _query_set.values("user_uuid")
            .annotate(
                whole_raffle_income=Sum("all_raffle_income"),
            )
            .values(
                "user_uuid",
                "whole_raffle_income",
            )
            .filter(whole_raffle_income__gt=0)
            .order_by("-whole_raffle_income")
        )
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserRankProfitView(View):
    """盈利排行榜"""

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(UserRankProfitSerializer)
        uid = IntFilterResolver().resolve_argument("uid", request)
        game_type_value = EnumFilterResolver(GameType).resolve_argument(
            "game_type", request
        )
        _query_set = Finance.objects.filter(deleted=False).filter(
            finance_type=FinanceType.wxuser.value
        )
        if game_type_value is not None:
            _query_set = _query_set.filter(game_type=game_type_value)

        date_resolver = DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt")
        filters = {"date": date_resolver}
        if date_resolver.supports_parameter("date", request):
            _query_set = join_filters(_query_set, request, filters)
        else:
            _date = datetime.now()
            _query_set = (
                _query_set.filter(createdAt__year=_date.year)
                .filter(createdAt__month=_date.month)
                .filter(createdAt__day=_date.day)
            )
        if uid is not None:
            user = Users.objects.filter(deleted=False).filter(id=uid).first()
            user_uuid = None
            if user is not None:
                user_uuid = user.uuid
            _query_set = _query_set.filter(user_uuid=user_uuid).filter(
                Q(all_raffle_income__gt=0) | Q(all_raffle_cost__gt=0)
            )

        _query_set = (
            _query_set.values("user_uuid")
            .annotate(
                whole_raffle_profit=Sum("all_raffle_profit"),
            )
            .values(
                "user_uuid",
                "whole_raffle_profit",
            )
            .order_by("-whole_raffle_profit")
        )
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserRecordRechargeView(View):
    """余额充值记录"""

    filters = {
        "uid": IntFilterResolver(field_name="Users.id", is_extra=True),
        "name": StringFilterResolver(field_name="Users.nickname", is_extra=True),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
        "type": EnumFilterResolver(
            UserRechargeType,
            field_name="recharge_type",
        ),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(UserRecordRechargeSerializer)
        _query_set = (
            UserRechargeOrder.objects.filter(deleted=False)
            .filter(state=OrderState.success.value)
            .extra(
                select={
                    "name": "Users.nickname",
                    "uid": "Users.id",
                    "type": "UserRechargeOrder.recharge_type",
                    "date": "UserRechargeOrder.createdAt",
                    "head_url": "Users.head_url",
                },
                tables=["Users"],
                where=[
                    "UserRechargeOrder.openid=Users.openid",
                    "Users.deleted=false",
                ],
            )
        )
        _query_set = _query_set.values(
            "name",
            "uid",
            "total_fee",
            "type",
            "out_trade_no",
            "date",
            "admin_uuid",
            "head_url",
        )
        _query_set = join_filters(_query_set, request, self.filters).order_by("-date")
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserRecordRefinedView(View):
    """提炼记录"""

    filters = {
        "uid": IntFilterResolver(field_name="Users.id", is_extra=True),
        "name": StringFilterResolver(field_name="Users.nickname", is_extra=True),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
        "orderid": StringFilterResolver(field_name="orderid", is_extra=True),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(UserRecordRefinedSerializer)
        _query_set = UserRefinedOrder.objects.filter(deleted=False).extra(
            select={
                "name": "Users.nickname",
                "uid": "Users.id",
                "orderid": "orderid",
                "date": "UserRefinedOrder.createdAt",
                "head_url": "Users.head_url",
            },
            tables=["Users"],
            where=[
                "UserRefinedOrder.user_uuid=Users.uuid",
                "Users.deleted=false",
            ],
        )
        _query_set = _query_set.values(
            "id",
            "uuid",
            "name",
            "uid",
            "head_url",
            "orderid",
            "sale_count",
            "sale_money",
            "date",
        )
        _query_set = join_filters(_query_set, request, self.filters).order_by("-date")
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserRecordRefinedGoodsView(View):
    """提炼记录详细"""

    _filters = {
        "order_refined_uuid": StringFilterResolver(required=True),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        """
        提炼记录详细
        """
        _query_set = UserRefinedOrder.objects.filter(deleted=False)
        _query_set = StringFilterResolver(required=True, field_name="uuid").filter(
            _query_set, "order_refined_uuid", request
        )

        user_refined_order = _query_set.first()

        if user_refined_order is None:
            raise NullErr

        _query_set = UserRefinedOrderGoods.objects.filter(deleted=False)
        _query_set = join_filters(_query_set, request, self._filters)
        _query_set = (
            _query_set.all().values("good_uuid").annotate(sum_count=Count("uuid"))
        )
        _query_set = _query_set.values(
            "good_uuid",
            "sum_count",
        )
        _query_set = _query_set.all()
        _list = []

        for refined_goods in _query_set:
            _refined_goods = UserDeliveryOrderDetailedGoodsSerializer(
                refined_goods
            ).data
            _list.append(_refined_goods)

        _data = {
            "code": 0,
            "msg": "ok",
            "data": {
                "list": _list,
                "sum_price": user_refined_order.sale_money,
                "sum_count": user_refined_order.sale_count,
            },
        }

        return JsonResponse(
            _data,
            status=status.HTTP_200_OK,
        )


class UserRaffleRecordView(View):
    """用户抽赏记录"""

    _filters = {
        "uid": IntFilterResolver(),
        "name": StringFilterResolver(),
        "orderid": StringFilterResolver(),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        """
        用户抽赏记录
        """

        uid = self._filters.get("uid").resolve_argument("uid", request)

        _query_set = UserOrder.objects.filter(deleted=False)
        if uid is not None:
            user = Users.objects.filter(deleted=False).filter(id=uid).first()
            if user is not None:
                _query_set = _query_set.filter(user_uuid=user.uuid)
        _query_set = join_filters(
            _query_set, request, self._filters, by=["name", "orderid", "date"]
        )
        _query_set = _query_set.order_by("-createdAt").all()
        paginator = JQPagination(UserRaffleRecordSerializer)
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserRaffleRecordGoodsView(View):
    _filters = {
        "order_uuid": StringFilterResolver(required=True),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        """
        用户抽赏记录详细
        """
        _query_set = UserPackageGoods.objects.filter(deleted=False)
        _query_set = join_filters(_query_set, request, self._filters)
        _query_set = _query_set.extra(
            select={
                "name": "JuqiGood.name",
                "display_url": "JuqiGood.display_url",
                "price": "JuqiGood.price",
                "recovery_price": "JuqiGood.recovery_price",
                "game_type": "JuqiGood.game_type",
            },
            tables=["JuqiGood"],
            where=["JuqiGood.uuid=UserPackageGoods.good_uuid"],
        )
        _query_set = _query_set.values(
            "name",
            "display_url",
            "price",
            "recovery_price",
            "game_type",
            "good_level_title",
            "order_num",
            "createdAt",
        ).annotate(count=Value(1))
        _query_set = _query_set.order_by("-createdAt").all()
        _list = []
        sum_price = 0

        for record_goods in _query_set:
            _record_goods = UserRaffleRecordGoodsSerializer(record_goods).data
            price = _record_goods["price"]  # 获取价格
            sum_price += price  # 统计价格
            _list.append(_record_goods)

        _data = {
            "code": 0,
            "msg": "ok",
            "data": {"list": _list, "sum_price": sum_price, "sum_count": len(_list)},
        }

        return JsonResponse(
            _data,
            status=status.HTTP_200_OK,
        )


class UserRecordWithdrawView(View):
    """魂晶提现记录"""

    filters = {
        "uid": IntFilterResolver(field_name="Users.id", is_extra=True),
        "name": StringFilterResolver(field_name="Users.nickname", is_extra=True),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(UserRecordWithdrawSerializer)

        _query_set = UserWithdraw.objects.filter(deleted=False).extra(
            select={
                "name": "Users.nickname",
                "uid": "Users.id",
                "date": "UserWithdraw.createdAt",
                "head_url": "Users.head_url",
                "manager": "JuqiAdmin.user",
            },
            tables=["Users", "JuqiAdmin"],
            where=[
                "UserWithdraw.user_uuid=Users.uuid",
                "UserWithdraw.admin_uuid=JuqiAdmin.uuid",
                "Users.deleted=false",
                "JuqiAdmin.deleted=false",
            ],
        )
        _query_set = _query_set.values(
            "id", "name", "uid", "withdraw_money", "date", "head_url", "manager"
        )
        _query_set = join_filters(_query_set, request, self.filters).order_by("-date")
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserRecordScoreView(View):
    """魂晶提现记录"""

    filters = {
        "uid": IntFilterResolver(field_name="Users.id", is_extra=True),
        "name": StringFilterResolver(field_name="Users.nickname", is_extra=True),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        paginator = JQPagination(UserRecordScoreSerializer)
        _query_set = UserScoreRecord.objects.filter(deleted=False).extra(
            select={
                "name": "Users.nickname",
                "uid": "Users.id",
                "date": "UserScoreRecord.createdAt",
                "head_url": "Users.head_url",
            },
            tables=["Users"],
            where=[
                "UserScoreRecord.user_uuid=Users.uuid",
                "Users.deleted=false",
            ],
        )
        _query_set = _query_set.values(
            "id",
            "name",
            "uid",
            "score",
            "new_score",
            "detail",
            "date",
            "head_url",
            "manager",
        )
        _query_set = join_filters(_query_set, request, self.filters).order_by("-date")
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class FinanceView(View):
    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        finance_type = request.GET.get("finance_type", None)
        _finance_type = FinanceType[finance_type].value

        paginator = JQPagination(FinanceSerializer)
        objs = Finance.objects.filter(finance_type=_finance_type).filter(deleted=False)

        _data = paginator.paginate(objs, request)

        return JsonResponse(
            _data,
            status=status.HTTP_200_OK,
        )


class WebSettingsView(View):
    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        web_settings = get_web_settings()
        _data = WebSettingsSerializer(web_settings).data
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )

    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        data: dict = JSONParser().parse(request)
        goods_recycle_less_money = int(data.get("goods_recycle_less_money"))
        data["goods_recycle_less_money"] = goods_recycle_less_money
        web_settings_ser = WebSettingsSerializer(
            instance=get_web_settings(locked=True), data=data, partial=True
        )
        web_settings_ser.is_valid(raise_exception=True)

        web_settings_ser.save()

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": web_settings_ser.data},
            status=status.HTTP_200_OK,
        )


class UserRecordPurchaseGoods(View):
    # 购买记录
    _filters = {
        "uid": IntFilterResolver(is_extra=True, field_name="Users.id"),
        "game_uuid": StringFilterResolver(
            required=True, is_uuid=True, is_extra=True, field_name="UserOrder.game_uuid"
        ),
        "game_type": EnumFilterResolver(
            GameType, required=True, is_extra=True, field_name="UserOrder.game_type"
        ),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        game_type = self._filters.get("game_type").resolve_argument(
            "game_type", request
        )
        box_num = IntFilterResolver().resolve_argument("box_num", request)  # 第几箱

        _game_type = GameType(game_type)
        table_name = get_game_type_table_name(game_type)

        _game_uuid_field_name = table_name + ".uuid"
        _game_name_field_name = table_name + ".name"
        _game_deleted_field_name = table_name + ".deleted"
        _game_price_field_name = table_name + ".price"
        _game_cover_url_field_name = table_name + ".cover_url"

        if _game_type == GameType.wuxianshang:
            _game_cover_url_field_name = table_name + ".display_url"

        _query_set = UserPackageGoods.objects.filter(deleted=False)

        if _game_type == GameType.yifanshang or _game_type == GameType.quanjushang:
            if box_num is None:
                raise NullErr
            _query_set = _query_set.filter(game_box_num=box_num)
        _query_set = (
            _query_set.extra(
                select={
                    "uid": "Users.id",
                    "user_uuid": "Users.uuid",
                    "user_name": "Users.nickname",
                    "user_head_url": "Users.head_url",
                    "game_type": "UserOrder.game_type",
                    "game_uuid": _game_uuid_field_name,
                    "game_name": _game_name_field_name,
                    "game_cover_url": _game_cover_url_field_name,
                    "game_price": _game_price_field_name,
                    "price": "UserOrder.price",
                    "good_uuid": "JuqiGood.uuid",
                    "good_name": "JuqiGood.name",
                    "good_display_url": "JuqiGood.display_url",
                    "good_price": "JuqiGood.price",
                    "good_recovery_price": "JuqiGood.recovery_price",
                    "date": "UserOrder.createdAt",
                },
                tables=["UserOrder", "Users", "JuqiGood", table_name],
                where=[
                    "UserPackageGoods.order_uuid=UserOrder.uuid",
                    "UserOrder.user_uuid=Users.uuid",
                    "UserPackageGoods.good_uuid=JuqiGood.uuid",
                    _game_uuid_field_name + "=UserOrder.game_uuid",
                    "UserOrder.deleted=false",
                    "Users.deleted=false",
                    "JuqiGood.deleted=false",
                    _game_deleted_field_name + "=false",
                ],
            )
            .annotate(num=F("order_num"), good_level_name=F("good_level_title"))
            .values(
                "uid",
                "user_uuid",
                "user_name",
                "user_head_url",
                "game_type",
                "game_uuid",
                "game_name",
                "game_cover_url",
                "game_box_num",
                "game_price",
                "price",
                "num",
                "good_uuid",
                "good_name",
                "good_display_url",
                "good_price",
                "good_recovery_price",
                "good_level_name",
                "date",
            )
        )

        _query_set = join_filters(_query_set, request, self._filters)
        date_dict = DateTimeRangeFilterResolver(
            "%Y-%m-%d", field_name=""
        ).resolve_argument("date", request)
        if date_dict is not None:
            date_keys = list(date_dict.keys())
            if date_keys.count("__range") > 0:
                __range = date_dict.get("__range")
                _query_set = _query_set.extra(
                    where=["%s <= UserOrder.createdAt", "UserOrder.createdAt < %s"],
                    params=__range,
                )
            elif date_keys.count("__gte") > 0:
                __gte = date_dict.get("__gte")
                _query_set = _query_set.extra(
                    where=["%s <= UserOrder.createdAt"],
                    params=[__gte],
                )
            elif date_keys.count("__lt") > 0:
                __lt = date_dict.get("__lt")
                _query_set = _query_set.extra(
                    where=["UserOrder.createdAt < %s"],
                    params=[__lt],
                )
        if _game_type == GameType.wuxianshang:
            _query_set = _query_set.order_by("-num")
        if _game_type == GameType.quanjushang:
            _query_set = _query_set.order_by("-good_recovery_price", "good_level_name")
        if _game_type == GameType.yifanshang:
            _query_set = _query_set.order_by("-num")

        pagination = JQPagination(UserRecordPurchaseGoodsSerializer)
        _data = pagination.paginate(_query_set, request)
        _filters = {
            "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
            "game_uuid": StringFilterResolver(
                required=True,
            ),
            "game_type": EnumFilterResolver(GameType, required=True),
        }
        uid = IntFilterResolver().resolve_argument("uid", request)

        _query_set = Finance.objects.filter(deleted=False).filter(
            finance_type=FinanceType.wxuser.value
        )
        if uid is not None:
            user = Users.objects.filter(deleted=False).filter(id=uid).first()
            user_uuid = None
            if user is not None:
                user_uuid = user.uuid
            _query_set = _query_set.filter(user_uuid=user_uuid)

        _query_set = join_filters(_query_set, request, _filters)
        _query_set: QuerySet
        _query_set = (
            _query_set.values("game_uuid")
            .annotate(
                sum_raffle_income=Sum("all_raffle_income"),
                sum_raffle_cost=Sum("all_raffle_cost"),
            )
            .values("sum_raffle_income", "sum_raffle_cost")
        )
        _data["sum_raffle_income"] = 0
        _data["sum_raffle_cost"] = 0
        _sum_list = list(_query_set)

        if len(_sum_list) > 0:
            _sum = _sum_list[0]
            if _sum is not None:
                _data["sum_raffle_income"] = _sum["sum_raffle_income"]
                _data["sum_raffle_cost"] = _sum["sum_raffle_cost"]

        # pprint(_query_set)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data}, status=status.HTTP_200_OK
        )


class UserRecordPurchaseGameNum(View):
    def _game_type_mapper_box_num(self, game_type, game_uuid):
        if game_type == GameType.yifanshang:
            return YifanshangGame.objects.filter(uuid=game_uuid).first().game_num
        if game_type == GameType.quanjushang:
            return QuanjushangGame.objects.filter(uuid=game_uuid).first().game_num
        return ValueErr

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        game_uuid = StringFilterResolver(required=True).resolve_argument(
            "game_uuid", request
        )
        game_type = EnumFilterResolver(GameType, required=True).resolve_argument(
            "game_type", request
        )

        _game_type = GameType(game_type)

        if _game_type == GameType.wuxianshang:
            raise ValueErr
        game_count = self._game_type_mapper_box_num(_game_type, game_uuid)
        return JsonResponse({"code": 0, "msg": "ok", "game_count": game_count})


class UserRecordPersonalDetailsView(View):
    # 购买记录个人详细信息
    _filters = {
        "uid": IntFilterResolver(is_extra=True, field_name="Users.id"),
        "game_uuid": StringFilterResolver(required=True),
        "game_type": EnumFilterResolver(GameType, required=True),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        _query_set = Finance.objects.filter(deleted=False).filter(
            finance_type=FinanceType.wxuser.value
        )
        _query_set = join_filters(
            _query_set, request, self._filters, by=["game_uuid", "game_type", "date"]
        )
        uid = IntFilterResolver().resolve_argument("uid", request)
        if uid is not None:
            user = Users.objects.filter(deleted=False).filter(id=uid).first()
            user_uuid = None
            if user is not None:
                user_uuid = user.uuid
            _query_set = _query_set.filter(user_uuid=user_uuid)

        _query_set = _query_set.values("user_uuid").annotate(
            raffle_income=Sum("all_raffle_income"),
            raffle_cost=Sum("all_raffle_cost"),
            raffle_profit=Sum("all_raffle_profit"),
        )
        _query_set = _query_set.values(
            "user_uuid",
            "raffle_income",
            "raffle_cost",
            "raffle_profit",
        )
        _all = _query_set.all()
        _list = []

        for _a in _all:
            _data = UserRecordPersonalDetailsSerializer(_a).data
            _query_set = UserOrder.objects.filter(deleted=False).filter(
                user_uuid=_a.get("user_uuid")
            )
            _query_set = join_filters(
                _query_set,
                request,
                self._filters,
                by=["game_uuid", "game_type", "date"],
            )
            sum_num = _query_set = (
                _query_set.values("user_uuid")
                .annotate(sum_num=Sum("num"))
                .values_list("sum_num", flat=True)
            )

            if sum_num is None or len(sum_num) <= 0:
                sum_num[0] = 0
            _data["purchase_num"] = sum_num[0]
            _list.append(_data)

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": {"list": _list, "sum_count": len(_list)}},
            status=status.HTTP_200_OK,
        )


class UserDeliveryOrderView(View):
    _filters = {
        "uid": IntFilterResolver(),
        "name": StringFilterResolver(field_name="nickname"),
        "orderid": StringFilterResolver(),
        "state": EnumFilterResolver(UserDeliveryOrderState),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        uid = self._filters.get("uid").resolve_argument("uid", request)
        name = self._filters.get("name").resolve_argument("name", request)

        _query_set = UserDeliveryOrder.objects.filter(deleted=False)
        if uid is not None or name is not None:
            user_query_set = Users.objects.filter(deleted=False)

            if uid is not None:
                user_query_set = user_query_set.filter(id=uid)
            if name is not None:
                user_query_set = user_query_set.filter(nickname=name)
            user = user_query_set.first()
            if user is not None:
                _query_set = _query_set.filter(user_uuid=user.uuid)
            else:
                _query_set = _query_set.filter(user_uuid=None)
        _query_set = join_filters(
            _query_set, request, self._filters, by=["orderid", "state", "date"]
        )
        _query_set = _query_set.order_by("-createdAt").all()
        paginator = JQPagination(UserDeliveryOrderSerializer)
        _data = paginator.paginate(_query_set, request)
        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class UserDeliveryOrderDetailedView(View):
    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        uuid = StringFilterResolver(required=True).resolve_argument("uuid", request)

        if uuid is None:
            raise UserDeliveryNullErr

        _query_set = UserDeliveryOrder.objects.filter(deleted=False).filter(uuid=uuid)
        delivery_order = _query_set.first()

        if delivery_order is None:
            raise UserDeliveryNullErr

        user_deliver_order_data = UserDeliveryOrderDetailedSerializer(
            delivery_order
        ).data

        user_express = (
            UserExpress.objects.filter(deleted=False)
            .filter(user_uuid=delivery_order.user_uuid)
            .first()
        )  # 获取默认地址

        user_express_info_data = None
        if user_express is not None and user_express.default_uuid is not None:
            user_express_info = (
                UserExpressInfo.objects.filter(deleted=False)
                .filter(uuid=user_express.default_uuid)
                .first()
            )
            if user_express_info is not None:
                user_express_info_data = UserExpressInfoSerializer(
                    user_express_info
                ).data

        user_deliver_order_data["user_express"] = user_express_info_data

        _data = {
            "code": 0,
            "msg": "ok",
            "data": user_deliver_order_data,
        }

        return JsonResponse(
            _data,
            status=status.HTTP_200_OK,
        )


class UserDeliveryOrderVerifyView(View):
    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        uuid = StringFilterResolver(required=True).resolve_argument("uuid", request)
        data = JSONParser().parse(request)

        if uuid is None:
            raise UserDeliveryNullErr
        if data is None:
            raise NullErr

        delivery_name = data.get("delivery_name")
        delivery_number = data.get("delivery_number")

        if (
            delivery_name is None
            or delivery_number is None
            or delivery_name == ""
            or delivery_number == ""
        ):
            raise NullErr

        _query_set = UserDeliveryOrder.objects.filter(deleted=False).filter(uuid=uuid)
        delivery_order = _query_set.select_for_update().first()

        if delivery_order is None:
            raise UserDeliveryNullErr

        if delivery_order.state != UserDeliveryOrderState.unshipped:
            raise UserDeliveredErr

        delivery_order.state = UserDeliveryOrderState.delivered
        delivery_order.delivery_name = delivery_name
        delivery_order.delivery_number = delivery_number
        delivery_order.delivery_datetime = datetime.now()
        delivery_order.save()

        return JsonResponse(
            {
                "code": 0,
                "msg": "ok",
            },
            status=status.HTTP_200_OK,
        )


class GameRuleView(View):
    _filters = {
        "uuid": StringFilterResolver(required=True),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        _query_set = GameRule.objects.filter(deleted=False)
        _query_set = join_filters(_query_set, request, self._filters)
        game_rule = _query_set.first()

        if game_rule is None:
            raise GameRuleNullErr

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": GameRuleSerializer(game_rule).data},
            status=status.HTTP_200_OK,
        )

    @check_admin
    @transaction.atomic()
    def post(self, request: WSGIRequest, *args, **kwargs):
        request_data = JSONParser().parse(request)

        _ser = GameRuleRequestBodySerializer(data=request_data)

        _ser.is_valid(raise_exception=True)

        game_rule = GameRule.objects.create(**request_data)

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": GameRuleSerializer(game_rule).data},
            status=status.HTTP_200_OK,
        )

    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        request_data = JSONParser().parse(request)

        uuid = request_data.get("uuid")
        if uuid is None:
            raise UserDeliveryNullErr
        _ser = GameRuleRequestBodySerializer(data=request_data)

        _ser.is_valid(raise_exception=True)

        row = (
            GameRule.objects.filter(deleted=False)
            .filter(uuid=uuid)
            .select_for_update()
            .update(**request_data)
        )

        if row <= 0:
            raise UserDeliveryNullErr

        return JsonResponse(
            {"code": 0, "msg": "ok"},
            status=status.HTTP_200_OK,
        )

    @check_admin
    @transaction.atomic()
    def delete(self, request: WSGIRequest, *args, **kwargs):
        _query_set = GameRule.objects.filter(deleted=False)
        _query_set = join_filters(_query_set, request, self._filters)

        row = _query_set.select_for_update().update(deleted=True)

        if row <= 0:
            raise UserDeliveryNullErr

        return JsonResponse(
            {"code": 0, "msg": "ok"},
            status=status.HTTP_200_OK,
        )


class GameRuleListView(View):
    _filters = {
        "key": StringFilterResolver(),
        "date": DateTimeRangeFilterResolver("%Y-%m-%d", field_name="createdAt"),
    }

    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        _query_set = GameRule.objects.filter(deleted=False)
        _query_set = join_filters(_query_set, request, self._filters)

        _query_set = _query_set.order_by("-createdAt").all()
        paginator = JQPagination(GameRuleSerializer)
        _data = paginator.paginate(_query_set, request)

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class GameRuleOptionView(View):
    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        _query_set = GameRule.objects.filter(deleted=False)
        _query_set = (
            _query_set.annotate(label=F("key"), value=F("uuid"))
            .values("label", "value")
            .order_by("-createdAt")
        )
        _data = []

        for _d in _query_set:
            _data.append(GameRuleOptionSerializer(_d).data)

        return JsonResponse(
            {"code": 0, "msg": "ok", "data": _data},
            status=status.HTTP_200_OK,
        )


class CorrectView(View):
    @check_admin
    @transaction.atomic()
    def put(self, request: WSGIRequest, *args, **kwargs):
        u = kwargs["user_info"]
        JuqiAdmin.objects.filter(uuid=u.uuid).select_for_update()
        user_package_goods_list = (
            UserPackageGoods.objects.filter(
                state__in=[
                    UserPackageGoodsState.unhandled.value,
                    UserPackageGoodsState.lock.value,
                ]
            )
            .extra(
                select={
                    "package_uuid": "UserPackageGoods.uuid",
                    "good_uuid": "JuqiGood.uuid",
                    "good_price": "JuqiGood.price",
                    "good_recovery_price": "JuqiGood.recovery_price",
                    "user_uuid": "UserPackageGoods.user_uuid",
                },
                tables=["JuqiGood"],
                where=[
                    "UserPackageGoods.good_uuid=JuqiGood.uuid",
                    "JuqiGood.deleted=false",
                ],
            )
            .values(
                "user_uuid",
                "good_uuid",
                "good_price",
                "good_recovery_price",
            )
        )
        user_list = Users.objects.all()
        new_user_list = []
        for user in user_list:
            user.delivery_amount = 0
            user.package_amount = 0
            new_user_list.append(user)
        Users.objects.bulk_update(
            new_user_list, fields=["delivery_amount", "package_amount"]
        )

        user_package_dict = dict()
        for user_package_goods in user_package_goods_list:
            _user_package = user_package_dict.get(user_package_goods.get("user_uuid"))
            if _user_package is None:
                _user_package = {
                    "user_uuid": user_package_goods.get("user_uuid"),
                    "sum_recovery_price": 0,
                }
            _user_package["sum_recovery_price"] += user_package_goods.get(
                "good_recovery_price"
            )
            user_package_dict[user_package_goods.get("user_uuid")] = _user_package
        user_uuid_list = list(user_package_dict.keys())
        user_list = Users.objects.filter(uuid__in=user_uuid_list).select_for_update()
        new_user_dict = {}
        for user in user_list:
            user_dict = user_package_dict.get(user.uuid.hex)
            if user_dict is None:
                raise NullErr

            sum_recovery_price = user_dict.get("sum_recovery_price")
            if sum_recovery_price is None:
                raise NullErr

            user.package_amount = sum_recovery_price
            new_user_dict[user.uuid] = user
        user_deliver_order_list = UserDeliveryOrder.objects.select_for_update().all()
        new_deliver_user_uuid_list = []
        deliver_user_dict = {}
        for user_deliver_order in user_deliver_order_list:
            user_deliver_order: UserDeliveryOrder
            user = new_user_dict.get(user_deliver_order.user_uuid)
            if user is None:
                new_deliver_user_uuid_list.append(user_deliver_order.user_uuid)
            deliver_user = deliver_user_dict.get(user_deliver_order.user_uuid)
            _today = user_deliver_order.createdAt.today()
            if deliver_user is None:
                deliver_user = {}
            deliver_user_day = deliver_user.get(_today)
            if deliver_user_day is None:
                deliver_user_day = {
                    "user_uuid": user_deliver_order.user_uuid,
                    "sum_recovery_price": 0,
                }
            deliver_user_day[
                "sum_recovery_price"
            ] += user_deliver_order.sum_recovery_price
            deliver_user[_today] = deliver_user_day
            deliver_user_dict[user_deliver_order.user_uuid] = deliver_user

        new_deliver_user_uuid_list = list(set(new_deliver_user_uuid_list))
        new_deliver_user_list = Users.objects.filter(
            uuid__in=new_deliver_user_uuid_list
        )

        for new_deliver_user in new_deliver_user_list:
            new_user_dict[new_deliver_user.uuid] = new_deliver_user
        new_fin = []
        for user_uuid in deliver_user_dict:
            user = new_user_dict.get(user_uuid)
            if user is None:
                raise NullErr
            user.delivery_amount = 0
            deliver_user = deliver_user_dict.get(user_uuid)
            for _today in deliver_user:
                _today_deliver_user = deliver_user.get(_today)
                user.delivery_amount += _today_deliver_user.get("sum_recovery_price")
                fin = get_wxuser_recharge_withdraw_finance(user_uuid, _today)
                fin.all_delivery_amount = _today_deliver_user.get("sum_recovery_price")
                new_fin.append(fin)
            new_user_dict[user_uuid] = user

        Users.objects.bulk_update(
            new_user_dict.values(), fields=["delivery_amount", "package_amount"]
        )

        Finance.objects.bulk_update(new_fin, fields=["all_delivery_amount"])

        return JsonResponse(
            {"code": 0, "msg": "ok"},
            status=status.HTTP_200_OK,
        )


class HomeView(View):
    @check_admin
    def get(self, request: WSGIRequest, *args, **kwargs):
        _now = datetime.now()
        _today = _now - timedelta(days=1)

        _now_fin = (
            Finance.objects.filter(deleted=False)
            .filter(finance_type=FinanceType.wxuser.value)
            .filter(finance_status=FinanceStatus.user)
            .filter(createdAt__year=_now.year)
            .filter(createdAt__month=_now.month)
            .filter(createdAt__day=_now.day)
            .values("user_uuid")
            .aggregate(
                whole_recharge=Sum(F("all_recharge") + F("all_admin_recharge")),
                whole_raffle_income=Sum("all_raffle_income"),
                whole_raffle_cost=Sum("all_raffle_cost"),
                whole_raffle_profit=Sum("all_raffle_profit"),
            )
        )

        _today_fin = (
            Finance.objects.filter(deleted=False)
            .filter(finance_type=FinanceType.wxuser.value)
            .filter(finance_status=FinanceStatus.user)
            .filter(createdAt__year=_today.year)
            .filter(createdAt__month=_today.month)
            .filter(createdAt__day=_today.day)
            .values("user_uuid")
            .aggregate(
                whole_recharge=Sum(F("all_recharge") + F("all_admin_recharge")),
                whole_raffle_income=Sum("all_raffle_income"),
                whole_raffle_cost=Sum("all_raffle_cost"),
                whole_raffle_profit=Sum("all_raffle_profit"),
            )
        )

        uid_list = get_web_settings_statistical_exclude_user_uid_list()

        _sum_user = Users.objects.exclude(id__in=uid_list).aggregate(
            sum_stored_money=Sum("stored_money"),
            sum_hunjing=Sum("hunjing"),
            sum_score=Sum("score"),
            sum_package_amount=Sum("package_amount"),
        )

        _user_count = Users.objects.count()

        _new_user_count = (
            Users.objects.filter(createdAt__year=_now.year)
            .filter(createdAt__month=_now.month)
            .filter(createdAt__day=_now.day)
            .count()
        )

        _new_shipment_count = (
            UserShipmentOrder.objects.filter(createdAt__year=_now.year)
            .filter(createdAt__month=_now.month)
            .filter(createdAt__day=_now.day)
            .count()
        )

        _data = {
            "now": HomeFinSerializer(_now_fin).data,
            "today": HomeFinSerializer(_today_fin).data,
            "sum_user": HomeUserSerializer(_sum_user).data,
            "user_count": _user_count,
            "new_user_count": _new_user_count,
            "new_shipment_count": _new_shipment_count,
        }

        return JsonResponse(
            {"code": 0, "msg": "ok", "date": _data},
            status=status.HTTP_200_OK,
        )
